import fs from 'fs';
import path from 'path';

export function loadSecrets(secretsPath = './secrets') {
  // load env from ./secrets
  const secretFiles = [];
  let secretsData: any = {};
  if (secretsPath && secretsPath.endsWith('.json')) {
    secretFiles.push(secretsPath);
  } else if (fs.existsSync(secretsPath)) {
    const allSecretFiles = fs
      .readdirSync(secretsPath)
      .filter(f => !f.includes('..'));
    console.log('🚀 ~ loadSecrets ~ allSecretFiles:', allSecretFiles);
    for (const fileName of allSecretFiles) {
      if (fileName) {
        const secretFile = path.join(secretsPath, fileName);
        secretFiles.push(secretFile);
      }
    }
  }

  if (secretFiles.length > 0) {
    const objectOfFiles = secretFiles.map(file => {
      let secretData = {};
      if (fs.existsSync(file)) {
        secretData = JSON.parse(fs.readFileSync(file, 'utf-8'));
        console.info(`secret file loaded: ${file}`);
      } else {
        console.error(`secret file not found: ${file}`);
      }
      return secretData;
    });
    secretsData = Object.assign({}, ...objectOfFiles);
  } else {
    const msg = '--- error: no secrets mounted! ---';
    console.error(msg);
  }

  return secretsData;
}
